﻿using Common;
using MsgPush.Contract;
using System;
using System.ServiceModel;
using System.Threading;
using System.Timers;

namespace JTE_WCF_Client
{
    public class JTE_Client
    {

        public IMsgPushService pushProxy; 
        private DuplexChannelFactory<IMsgPushService> channel;
        private System.Timers.Timer timer;



        public bool Login(string usercode,string pwd)
        {
            try
            {
                Model.UserService.THUser hUser = UserConnect.VerifySuccess(Session.GetSession.SessionId(), usercode, pwd);
                if (hUser == null) return false;
                new Thread((ThreadStart)(() => this.StartMsgPushService()))
                {
                    IsBackground = true
                }.Start();

                timer = new System.Timers.Timer();
                timer.Interval = 5000;
                timer.Elapsed += timer_Elapsed;
                timer.Start();
            }
            catch (Exception)
            {
                
            }


            return true;
        }

        private void StartMsgPushService()
        {
            try
            {
                this.StartMsgChannel();
                this.HeartBeatTestConn();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private void HeartBeatTestConn()
        {
            while (true)
            {
                try
                {
                    this.pushProxy.TestConnection();
                    Thread.Sleep(5000);
                }
                catch (TimeoutException ex)
                {
                    (this.pushProxy as ICommunicationObject).Abort();
                    this.StartMsgChannel();
                }
                catch (CommunicationException ex)
                {
                    (this.pushProxy as ICommunicationObject).Abort();
                    this.StartMsgChannel();
                }
                catch (Exception ex)
                {
                    (this.pushProxy as ICommunicationObject).Close();
                    this.StartMsgChannel();
                }
            }
        }
        public void Close()
        {
            pushProxy.UnSubscribe(Session.GetSession.SessionId());
        }
        private void StartMsgChannel()
        {
            try
            {
                this.channel = new DuplexChannelFactory<IMsgPushService>(new InstanceContext((object)new MsgPushCallback()), "push");
                this.pushProxy = this.channel.CreateChannel();
                this.pushProxy.Subscribe(Session.GetSession.SessionId());
                Console.WriteLine("连接消息推送服务器成功");
                //Messenger.Default.Register<NotificationMessage<NotificationMsg>>((object)this, (Action<NotificationMessage<NotificationMsg>>)(nm =>
                //{
                //    if (nm.Notification == "标记为已处理")
                //    {
                //        this.MarkedHandled(nm.Content);
                //    }
                //    else
                //    {
                //        if (!(nm.Notification == "查房请求") && !(nm.Notification == "收到查房请求答复-查房中。。。") && !(nm.Notification == "查房OK答复"))
                //            return;
                //        this.pushProxy.SendNotificationMsg(nm.Content.Body, nm.Content.Type, nm.Content.Modules, Session.GetSession.SessionId(), nm.Content.Action);
                //    }
                //}));
            }
            catch (Exception ex)
            {
                Console.WriteLine("开启消息推送服务异常" + ex.Message);
            }
        }

        private void MarkedHandled(NotificationMsg notificationMsg)
        {
            if (notificationMsg == null)
                return;
            this.pushProxy.MarkHandled(notificationMsg.Id, Session.GetSession.SessionId());
        }

        private void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                this.pushProxy.TestConnection();
            }
            catch (TimeoutException ex)
            {
                (this.pushProxy as ICommunicationObject).Abort();
                Console.WriteLine("心跳消息推送通道超时异常，开始重新连接" + ex.Message);
                this.StartMsgChannel();
            }
            catch (CommunicationException ex)
            {
                (this.pushProxy as ICommunicationObject).Abort();

                Console.WriteLine("心跳消息推送通道超时异常，开始重新连接" + ex.Message);
                this.StartMsgChannel();
            }
            catch (Exception ex)
            {
                (this.pushProxy as ICommunicationObject).Close();
                Console.WriteLine("心跳消息推送通道未知异常，开始重新连接" + ex.Message);
                this.StartMsgChannel();
            }
        }
    }
}